package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author gsy
 * @date 2021年09月07日20:14
 * Description
 */
@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {

    @Autowired
    private CartInfoService cartInfoService;

    //加入购物车
    @PostMapping("/addCart/{skuId}/{skuNum}")
    public void addCart(@PathVariable Long skuId, @PathVariable Integer skuNum, HttpServletRequest request) {
        //用户id
        String userId = AuthContextHolder.getUserId(request);
        //有真实用户添加真实用户id，没有添加临时用户id
        if (StringUtils.isEmpty(userId)) {
            userId = AuthContextHolder.getUserTempId(request);
        }
//        System.out.println(userId);
//        System.out.println(userTempId);
        cartInfoService.addCart(skuId, skuNum,userId);

    }
    //回显添加的商品信息
    @GetMapping("/findCartInfo/{skuId}")
    public CartInfo findCartInfo(@PathVariable Long skuId) {
        return cartInfoService.findCartInfo(skuId);

    }
    //查询购物车列表
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        List<CartInfo> cartInfoList =  cartInfoService.cartList(userId,userTempId);

        return Result.ok(cartInfoList);
    }
    //复选框选中购物车
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,@PathVariable Integer isChecked,HttpServletRequest request){
        //用户真实id
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            userId =AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.checkCart(skuId,isChecked,userId);

        return Result.ok();

    }

    //查询购物车选中的商品清单
    @GetMapping("/getCartCheckedList/{userId}")
    public List<CartInfo> getCartCheckedList(@PathVariable String userId){
        return cartInfoService.getCartCheckedList(userId);
    }
}
